//
//  NSData+Extension.swift
//  zhengwutong
//
//  Created by wangshuguan on 16/9/5.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
extension Data {
    func utf8Data() -> Data {
        var bytes:UnsafeBufferPointer<UInt8>?
        withUnsafeBytes { (unsafeRawBufferPointer) -> Void in
            let unsafeBufferPointer = unsafeRawBufferPointer.bindMemory(to: UInt8.self)
            let unsafePointer:UnsafePointer<UInt8> = unsafeBufferPointer.baseAddress!
            let b = UnsafeBufferPointer(start: unsafePointer, count: count)
            bytes = b
        }
        let replacement = "�".data(using: String.Encoding.utf8)
        var resData = Data(capacity: self.count)
        var index = 0
        while index < self.count {
            var len = 0
            if (bytes?[index])! & 0x80 == 0 {
                len = 1
            } else if (bytes?[index])! & 0xE0 == 0xC0 {
                if (bytes?[index] != 0xC0 && bytes?[index] != 0xC1)
                {
                    len = 2
                }
            }else if ((bytes?[index])!&0xF0) == 0xE0 {
                len = 3
            }else if ((bytes?[index])!&0xF8) == 0xF0{
                if (bytes?[index] != 0xF5 && bytes?[index] != 0xF6 && bytes?[index] != 0xF7)
                {
                    len = 4;
                }
            }
            //无法识别
            if (len == 0)
            {
                resData.append(replacement!)
                index += 1
                continue
            }
            
            
            var validLen = 1;
            while (validLen < len && index+validLen < self.count)
            {
                if (((bytes?[index+validLen])! & 0xC0) != 0x80){
                    validLen += 1
                    break
                }
            }
            
            //有效字节等于编码要求的字节数表示合法,否则不合法
            if (validLen == len)
            {
                resData.append((resData.subdata(in: index..<len)))
            }else
            {
                resData.append(replacement!)
            }
            
            //移动下标
            index += validLen;
        }
        return resData
    }
    func utf8String() -> String? {
        return String(data: self as Data, encoding: String.Encoding.utf8)
    }
    var gb2312String:String{
        get{
            var str = String(data: self, encoding: .utf8)
            if str == nil{
                str = String(data: self, encoding: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(1586)))
            }
            return str ?? ""
        }
    }
}
